import time
from threading import Thread, Lock


# 交易类
class Account:
    def __init__(self, _id, balance, lock):
        # 用户
        self.id = _id
        # 存款
        self.balance = balance
        # 锁
        self.lock = lock

    # 取钱
    def withdraw(self, amount):
        self.balance -= amount

    # 存钱
    def deposit(self, amount):
        self.balance += amount

    def get_balance(self):
        return self.balance


def transfer(from_, to, amount):
    # 锁住自己的账户。上锁成功返回True
    if from_.lock.acquire():
        # 自己账户金额减少
        from_.withdraw(amount)
        time.sleep(0.5)
        if to.lock.acquire():
            # 对方账户金额增加
            to.deposit(amount)
            to.lock.release()
        from_.lock.release()
    print('转账完成')


rachel = Account('Rachel', 5000, Lock())
frank = Account('Frank', 89000, Lock())

t = Thread(target=transfer, args=(rachel, frank, 1500))
t2 = Thread(target=transfer, args=(frank, rachel, 1000))
t.start()
t2.start()
t.join()
t2.join()

print('rachel:', rachel.get_balance())
print('frank:', frank.get_balance())
